<template>
  <div class="monitor-alert-container">
    <a-tabs v-model:activeKey="activeTab">
      <a-tab-pane key="1" tab="接口监控">
        <a-card class="filter-card">
          <a-row :gutter="20">
            <a-col :span="6">
              <a-range-picker
                v-model:value="dateRange"
                style="width: 100%"
                :placeholder="['开始时间', '结束时间']"
              />
            </a-col>
            <a-col :span="4">
              <a-select
                v-model:value="apiFilter"
                placeholder="选择接口"
                allow-clear
                style="width: 100%"
              >
                <a-select-option value="/api/users">/api/users</a-select-option>
                <a-select-option value="/api/products">/api/products</a-select-option>
              </a-select>
            </a-col>
            <a-col :span="4">
              <a-select
                v-model:value="metricFilter"
                placeholder="选择指标"
                allow-clear
                style="width: 100%"
              >
                <a-select-option value="latency">响应时间</a-select-option>
                <a-select-option value="error_rate">错误率</a-select-option>
                <a-select-option value="throughput">吞吐量</a-select-option>
              </a-select>
            </a-col>
            <a-col :span="4">
              <a-button @click="filterMetrics">筛选</a-button>
            </a-col>
          </a-row>
        </a-card>

        <a-row :gutter="20" class="mb-20">
          <a-col :span="6">
            <a-card class="metric-card">
              <div class="metric-header">
                <span class="metric-title">平均响应时间</span>
                <span class="metric-value">125<small>ms</small></span>
              </div>
              <div class="metric-trend">
                <span class="trend up">↑ 5.2%</span>
              </div>
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card class="metric-card">
              <div class="metric-header">
                <span class="metric-title">错误率</span>
                <span class="metric-value">0.8<small>%</small></span>
              </div>
              <div class="metric-trend">
                <span class="trend down">↓ 0.3%</span>
              </div>
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card class="metric-card">
              <div class="metric-header">
                <span class="metric-title">今日请求数</span>
                <span class="metric-value">24,568</span>
              </div>
              <div class="metric-trend">
                <span class="trend up">↑ 12.4%</span>
              </div>
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card class="metric-card">
              <div class="metric-header">
                <span class="metric-title">可用性</span>
                <span class="metric-value">99.9<small>%</small></span>
              </div>
              <div class="metric-trend">
                <span class="trend same">→ 0.0%</span>
              </div>
            </a-card>
          </a-col>
        </a-row>

        <a-card class="chart-card">
          <template #title>
            <span>性能趋势</span>
          </template>
          <div ref="metricChart" style="height: 400px;"></div>
        </a-card>
      </a-tab-pane>
      
      <a-tab-pane key="2" tab="告警规则">
        <a-card class="header-card">
          <a-row>
            <a-col :span="12">
              <a-input-search
                v-model:value="searchText"
                placeholder="搜索告警规则"
                style="width: 300px"
                @search="onSearch"
              />
            </a-col>
            <a-col :span="12" class="text-right">
              <a-button type="primary" @click="showCreateModal">
                <PlusOutlined />
                添加告警规则
              </a-button>
            </a-col>
          </a-row>
        </a-card>

        <a-card class="content-card">
          <a-table
            :data-source="alertRuleList"
            :columns="columns"
            :pagination="pagination"
            @change="handleTableChange"
            :loading="loading"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'status'">
                <a-tag :color="record.status === 1 ? 'success' : 'error'">
                  {{ record.status === 1 ? '启用' : '禁用' }}
                </a-tag>
              </template>
              <template v-else-if="column.dataIndex === 'action'">
                <a-space>
                  <a-button type="link" @click="editAlertRule(record)">编辑</a-button>
                  <a-button type="link" @click="deleteAlertRule(record)">删除</a-button>
                  <a-button type="link" @click="toggleStatus(record)">
                    {{ record.status === 1 ? '禁用' : '启用' }}
                  </a-button>
                </a-space>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-tab-pane>
      
      <a-tab-pane key="3" tab="告警历史">
        <a-card class="filter-card">
          <a-row :gutter="20">
            <a-col :span="6">
              <a-range-picker
                v-model:value="alertDateRange"
                style="width: 100%"
                :placeholder="['开始时间', '结束时间']"
              />
            </a-col>
            <a-col :span="4">
              <a-select
                v-model:value="levelFilter"
                placeholder="告警级别"
                allow-clear
                style="width: 100%"
              >
                <a-select-option value="critical">严重</a-select-option>
                <a-select-option value="warning">警告</a-select-option>
                <a-select-option value="info">提示</a-select-option>
              </a-select>
            </a-col>
            <a-col :span="4">
              <a-button @click="filterAlerts">筛选</a-button>
            </a-col>
          </a-row>
        </a-card>

        <a-card class="content-card">
          <a-table
            :data-source="alertHistoryList"
            :columns="alertColumns"
            :pagination="alertPagination"
            @change="handleAlertTableChange"
            :loading="alertLoading"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'level'">
                <a-tag :color="getLevelColor(record.level)">{{ getLevelText(record.level) }}</a-tag>
              </template>
              <template v-else-if="column.dataIndex === 'status'">
                <a-tag :color="record.status === 'resolved' ? 'success' : 'warning'">
                  {{ record.status === 'resolved' ? '已解决' : '未解决' }}
                </a-tag>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-tab-pane>
    </a-tabs>

    <!-- 添加/编辑告警规则 Modal -->
    <a-modal
      v-model:open="modalVisible"
      :title="editingAlertRule ? '编辑告警规则' : '添加告警规则'"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <a-form :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="规则名称" required>
          <a-input v-model:value="form.name" placeholder="请输入规则名称" />
        </a-form-item>
        <a-form-item label="监控接口">
          <a-select v-model:value="form.api" placeholder="请选择监控接口">
            <a-select-option value="/api/users">/api/users</a-select-option>
            <a-select-option value="/api/products">/api/products</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="监控指标">
          <a-select v-model:value="form.metric" placeholder="请选择监控指标">
            <a-select-option value="latency">响应时间</a-select-option>
            <a-select-option value="error_rate">错误率</a-select-option>
            <a-select-option value="throughput">吞吐量</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="比较条件">
          <a-row :gutter="10">
            <a-col :span="12">
              <a-select v-model:value="form.operator">
                <a-select-option value="gt">&gt;</a-select-option>
                <a-select-option value="lt">&lt;</a-select-option>
                <a-select-option value="eq">=</a-select-option>
              </a-select>
            </a-col>
            <a-col :span="12">
              <a-input-number v-model:value="form.threshold" style="width: 100%" />
            </a-col>
          </a-row>
        </a-form-item>
        <a-form-item label="告警级别">
          <a-select v-model:value="form.level" placeholder="请选择告警级别">
            <a-select-option value="critical">严重</a-select-option>
            <a-select-option value="warning">警告</a-select-option>
            <a-select-option value="info">提示</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="通知方式">
          <a-checkbox-group v-model:value="form.notifications">
            <a-checkbox value="email">邮件</a-checkbox>
            <a-checkbox value="sms">短信</a-checkbox>
            <a-checkbox value="webhook">Webhook</a-checkbox>
          </a-checkbox-group>
        </a-form-item>
        <a-form-item label="状态">
          <a-switch
            v-model:checked="form.status"
            checked-children="启用"
            un-checked-children="禁用"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { PlusOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import dayjs from 'dayjs';

export default {
  name: 'MonitorAlert',
  components: {
    PlusOutlined
  },
  data() {
    return {
      activeTab: '1',
      dateRange: [dayjs().subtract(7, 'day'), dayjs()],
      alertDateRange: [dayjs().subtract(1, 'day'), dayjs()],
      apiFilter: undefined,
      metricFilter: undefined,
      levelFilter: undefined,
      searchText: '',
      loading: false,
      alertLoading: false,
      modalVisible: false,
      editingAlertRule: null,
      metricChart: null,
      form: {
        name: '',
        api: '/api/users',
        metric: 'latency',
        operator: 'gt',
        threshold: 1000,
        level: 'warning',
        notifications: ['email'],
        status: true
      },
      alertRuleList: [
        {
          id: 1,
          name: '用户接口响应时间过长',
          api: '/api/users',
          metric: 'latency',
          condition: '> 1000ms',
          level: 'warning',
          status: 1,
          createTime: '2023-09-01 10:00:00'
        },
        {
          id: 2,
          name: '产品接口错误率过高',
          api: '/api/products',
          metric: 'error_rate',
          condition: '> 5%',
          level: 'critical',
          status: 1,
          createTime: '2023-09-01 10:05:00'
        }
      ],
      alertHistoryList: [
        {
          id: 1,
          name: '用户接口响应时间过长',
          level: 'warning',
          message: '接口/api/users响应时间超过1000ms',
          time: '2023-09-01 15:30:25',
          status: 'resolved'
        },
        {
          id: 2,
          name: '产品接口错误率过高',
          level: 'critical',
          message: '接口/api/products错误率超过5%',
          time: '2023-09-01 14:20:10',
          status: 'resolved'
        },
        {
          id: 3,
          name: '用户接口响应时间过长',
          level: 'warning',
          message: '接口/api/users响应时间超过1000ms',
          time: '2023-09-01 12:15:45',
          status: 'unresolved'
        }
      ],
      columns: [
        {
          title: '规则名称',
          dataIndex: 'name',
          key: 'name'
        },
        {
          title: '监控接口',
          dataIndex: 'api',
          key: 'api'
        },
        {
          title: '监控指标',
          dataIndex: 'metric',
          key: 'metric'
        },
        {
          title: '触发条件',
          dataIndex: 'condition',
          key: 'condition'
        },
        {
          title: '告警级别',
          dataIndex: 'level',
          key: 'level'
        },
        {
          title: '状态',
          dataIndex: 'status',
          key: 'status'
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          key: 'createTime'
        },
        {
          title: '操作',
          dataIndex: 'action',
          key: 'action'
        }
      ],
      alertColumns: [
        {
          title: '告警名称',
          dataIndex: 'name',
          key: 'name'
        },
        {
          title: '告警级别',
          dataIndex: 'level',
          key: 'level'
        },
        {
          title: '告警内容',
          dataIndex: 'message',
          key: 'message'
        },
        {
          title: '告警时间',
          dataIndex: 'time',
          key: 'time'
        },
        {
          title: '状态',
          dataIndex: 'status',
          key: 'status'
        }
      ],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 2
      },
      alertPagination: {
        current: 1,
        pageSize: 10,
        total: 3
      }
    };
  },
  mounted() {
    this.initCharts();
  },
  beforeUnmount() {
    if (this.metricChart) {
      this.metricChart.dispose();
    }
  },
  methods: {
    initCharts() {
      this.$nextTick(() => {
        this.initMetricChart();
      });
    },
    initMetricChart() {
      const chartDom = this.$refs.metricChart;
      if (!chartDom) return;
      
      if (this.metricChart) {
        this.metricChart.dispose();
      }
      
      this.metricChart = echarts.init(chartDom);
      
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['响应时间(ms)', '错误率(%)']
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: ['00:00', '04:00', '08:00', '12:00', '16:00', '20:00', '24:00']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '响应时间(ms)',
            type: 'line',
            data: [120, 132, 101, 134, 90, 230, 210],
            smooth: true,
            lineStyle: {
              width: 2
            }
          },
          {
            name: '错误率(%)',
            type: 'line',
            data: [0.5, 0.8, 0.6, 1.2, 0.9, 2.5, 1.8],
            smooth: true,
            lineStyle: {
              width: 2
            }
          }
        ]
      };
      
      this.metricChart.setOption(option);
    },
    filterMetrics() {
      message.success('筛选成功');
    },
    onSearch() {
      message.success('搜索功能已触发');
    },
    showCreateModal() {
      this.editingAlertRule = null;
      this.form = {
        name: '',
        api: '/api/users',
        metric: 'latency',
        operator: 'gt',
        threshold: 1000,
        level: 'warning',
        notifications: ['email'],
        status: true
      };
      this.modalVisible = true;
    },
    editAlertRule(record) {
      this.editingAlertRule = record;
      this.form = { ...record };
      this.form.status = record.status === 1;
      this.modalVisible = true;
    },
    deleteAlertRule(record) {
      const that = this;
      this.$confirm({
        title: '确认删除',
        content: `确定要删除告警规则 "${record.name}" 吗？`,
        onOk() {
          // 模拟删除操作
          message.success('删除成功');
          that.alertRuleList = that.alertRuleList.filter(item => item.id !== record.id);
        }
      });
    },
    toggleStatus(record) {
      const index = this.alertRuleList.findIndex(item => item.id === record.id);
      this.alertRuleList[index].status = record.status === 1 ? 0 : 1;
      message.success(`${record.status === 1 ? '禁用' : '启用'}成功`);
    },
    filterAlerts() {
      message.success('筛选成功');
    },
    handleModalOk() {
      if (!this.form.name) {
        message.warning('请填写规则名称');
        return;
      }

      if (this.editingAlertRule) {
        // 编辑操作
        const index = this.alertRuleList.findIndex(item => item.id === this.editingAlertRule.id);
        this.alertRuleList[index] = {
          ...this.form,
          id: this.editingAlertRule.id,
          status: this.form.status ? 1 : 0,
          createTime: this.editingAlertRule.createTime
        };
        message.success('编辑成功');
      } else {
        // 新增操作
        this.alertRuleList.push({
          ...this.form,
          id: this.alertRuleList.length + 1,
          status: this.form.status ? 1 : 0,
          createTime: new Date().toLocaleString()
        });
        message.success('新增成功');
      }
      this.modalVisible = false;
    },
    handleModalCancel() {
      this.modalVisible = false;
    },
    handleTableChange(pagination) {
      this.pagination = { ...pagination };
    },
    handleAlertTableChange(pagination) {
      this.alertPagination = { ...pagination };
    },
    getLevelColor(level) {
      const colorMap = {
        critical: 'red',
        warning: 'orange',
        info: 'blue'
      };
      return colorMap[level] || 'default';
    },
    getLevelText(level) {
      const textMap = {
        critical: '严重',
        warning: '警告',
        info: '提示'
      };
      return textMap[level] || level;
    }
  }
};
</script>

<style scoped>
.monitor-alert-container {
  padding: 20px;
}

.mb-20 {
  margin-bottom: 20px;
}

.filter-card {
  margin-bottom: 20px;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header-card {
  margin-bottom: 20px;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.content-card,
.chart-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.text-right {
  text-align: right;
}

.metric-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.metric-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.metric-title {
  font-size: 14px;
  color: #666;
}

.metric-value {
  font-size: 24px;
  font-weight: bold;
}

.metric-value small {
  font-size: 14px;
  font-weight: normal;
}

.metric-trend {
  margin-top: 10px;
}

.trend.up {
  color: #f5222d;
}

.trend.down {
  color: #52c41a;
}

.trend.same {
  color: #1890ff;
}
</style>